import { ref, onMounted, onUnmounted } from "vue";

export default function useScript(options: string) {
  let script: HTMLScriptElement;
  const isSuccess = ref(false);

  const loadScript = new Promise((resolve, reject) => {
    onMounted(() => {
      script = document.createElement("script");
      script.type = "text/javascript";
      script.onload = () => {
        isSuccess.value = true;
        resolve(true);
      };
      script.onerror = () => {
        isSuccess.value = false;
        reject(new Error(`Failed to load script ${options}`));
      };
      script.src = options;
      document.head.appendChild(script);
    });
  });

  onUnmounted(() => {
    script && script.remove();
  });

  return {
    isSuccess,
    loadScript: () => loadScript
  };
}
